<?php

namespace app\controller\adminapi\user;

use app\common\model\addonAuth\UserAddon;
use app\common\model\addonAuth\UserAddonGroup;
use app\common\model\attachment\Attachment;
use app\common\model\attachment\AttachmentGroup;
use app\common\model\platform\Platform;
use app\common\model\user\UserGroup;
use app\common\model\user\User as UserModel;
use app\common\model\user\UserToken;
use app\common\model\user\UserWallet;
use hiduoke\services\FormBuilder as Form;
use app\common\controller\AdminController;
use app\common\model\addonAuth\AddonGroup;
use hiduoke\services\Random;

class User extends AdminController
{
    protected $notLogin = ['login'];

    /**
     * @var UserModel
     */
    public $UserModel = null;

    public function initialize()
    {
        $this->UserModel = new UserModel();
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $username = input("username", '');
        $password = input("password", '');
        if ($this->auth->login($username, $password) && !$this->auth->getError()) {
            $userinfo = $this->auth->getUserinfo();
            $userinfo['token'] = $this->auth->getToken();
            return $this->success("ok", $userinfo);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function info()
    {
        //TODO 这里需要判断运行环境来获取不同的userinfo
        return $this->success('ok', $this->userInfo);
    }

    /**
     * 退出登录
     * @return \think\response\Json
     */
    public function logout()
    {
        $this->auth->logout();
        return $this->success('yes');
    }

    //获取用户列表
    public function getList()
    {
        $data = $this->UserModel->getPageListData()->append(['group_name', 'wallet', 'addon_group_name']);
        $count = $this->UserModel->getPageListCount();
        return $this->success($count, $data);
    }

    /**
     * 获取用户编辑表单
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserForm()
    {
        $uid = input('uid');
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/user/setUserForm")->setMethod("POST");
        $user_group_options = UserGroup::getUserGroupOption();
        $addon_group_options = AddonGroup::getAddonGroupOption();
        $user = $this->UserModel::withSearch(['uid'], ['uid' => $uid])->append(['wallet'])->findOrEmpty();
        if (!$user->isEmpty()) {
            $title = "编辑用户";
            $rule[] = Form::input('uid', '用户ID', $user->uid ?? 0)->disabled(true);
            $rule[] = Form::input('username', '登录账号', $user->username ?? '')->disabled(true);
            $rule[] = Form::input('password', '修改密码', '')->placeholder("修改密码，不填则密码不改变");
        } else {
            $title = "新增用户";
            $rule[] = Form::input('username', '登录账号', "")->required();
            $rule[] = Form::input('password', '登录密码', "")->required();
        }

        $rule[] = Form::dkImage('avatar', '头像', $user->avatar ?? '')->appendToBody();
        $rule[] = Form::radio('is_admin', '是否为管理员', $user->is_admin ?? 0)
            ->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->appendControl(1, [
                Form::select("group_id", "管理用户组", $user->group_id ?? 0)->options($user_group_options)->filterable(true)
            ]);
        $rule[] = Form::select("addon_group_id", "应用组", $user->addon_group_id ?? 0)->options($addon_group_options)->filterable(true);
        $rule[] = Form::radio('status', '状态', $user->status ?? 0)->options([['label' => '正常', 'value' => 0], ['label' => '禁用', 'value' => -1]]);
        $rule[] = Form::input('phone', '电话', $user->phone ?? '');
        $rule[] = Form::input('remark', '备注', $user->remark ?? '');
        $form->setTitle($title)->setRule($rule);
        return $this->success('', Form::getFormData($form));
    }

    /**
     * 编辑和新增用户
     * @return \think\response\Json
     */
    public function setUserForm()
    {
        $formData = input('formData', []);
        $uid = isset($formData["uid"]) ? $formData["uid"] : 0;
        $user = $this->UserModel::withSearch(['uid'], ['uid' => $uid])->findOrEmpty();
        if ($user->isEmpty()) {
            //不存在为新增
            $msg = '新增成功';
            if ($this->UserModel::checkUnique(['username' => $formData['username']])) {
                return $this->error("用户名已存在");
            }
            $formData['salt'] = Random::alnum();
            $formData['password'] = $this->auth->getEncryptPassword($formData['password'], $formData['salt']);
        } else {
            $msg = '修改成功';
            if ($formData['password']) {
                $this->auth->changePwdByUid($formData['uid'], $formData['password']);
            }
            unset($formData['password']);
        }
        $user->save($formData);
        return $this->success($msg);
    }

    /**
     * 删除用户
     */
    public function deleteUser()
    {
        $uid = input("uid", 0);
        $this->UserModel->where(['uid' => $uid])->delete();
        return $this->success("删除成功");
    }


    public function getUserWalletForm()
    {
        $uid = input('uid');
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/user/setUserWalletForm")->setMethod("POST");
        $wallet = UserWallet::where(['uid' => $uid])->findOrEmpty();
        $title = "编辑用户资产";
        $rule[] = Form::hidden('uid', $wallet->uid ?? $uid);
        $rule[] = Form::number('wechat', '微信公众平台', $wallet->wechat ?? 0);
        $rule[] = Form::number('free', '自由平台', $wallet->free ?? 0);
        $rule[] = Form::number('douyin', '抖音', $wallet->douyin ?? 0);
        $rule[] = Form::number('work_wechat', '企业微信', $wallet->work_wechat ?? 0);
        $rule[] = Form::number('min_app', '小程序集', $wallet->min_app ?? 0);

        $form->setTitle($title)->setRule($rule);
        return $this->success('', Form::getFormData($form));
    }

    public function setUserWalletForm()
    {
        $formData = input('formData', []);
        $uid = isset($formData["uid"]) ? $formData["uid"] : 0;
        $wallet = UserWallet::where(['uid' => $uid])->findOrEmpty();
        $wallet->save($formData);
        return $this->success("修改成功");
    }

    /**
     * 删除用户
     */
    public function delete(){
        $uid = input('uid',0);
        (new UserAddon())->where(['uid'=>$uid])->delete();
        (new UserAddonGroup())->where(['uid'=>$uid])->delete();
        (new \app\common\model\user\UserPermission())->where(['uid'=>$uid])->delete();
        (new UserToken())->where(['uid'=>$uid])->delete();
        (new UserWallet())->where(['uid'=>$uid])->delete();
        (new Attachment())->where(['uid'=>$uid])->delete();
        (new AttachmentGroup())->where(['uid'=>$uid])->delete();
        (new Platform())->where(['uid'=>$uid])->delete();
        $this->UserModel->where(['uid'=>$uid])->delete();
        return $this->success("删除成功");
        // 删除用户 user
        // 删除应用 user_addon
        // 删除用户应用组 user_addon_group
        // 删除用户权限 user_permission
        // 用户附件 attachment
        // 用户附件组 attachment_group
        // 平台 platform
        // Token user_token
        // 删除用户钱包 user_wallet
    }
}
